﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LPrisaMVC.Entities;
using System.Data;

namespace LPrisaMVC.DAO
{
    public class DetalleCreditoDAO: MasterRepository, IDetalleCreditoDAO
    {
        public DETALLE_CREDITO GetDetalleCreditoByCreditoIdAndProductoId(int idCredito, int idProd)
        {
            return Context.DETALLE_CREDITO.Include("PRODUCTO")
                .Where(c => c.PRODUCTO.Id.Equals(idProd) && c.CreditoId.Equals(idCredito)).SingleOrDefault();
        }

        public List<DETALLE_CREDITO> GetFromDetalleCreditoByProductoDescAndCreditoId(string descripcion, int idCredito)
        {
            if (descripcion != null)
            {
                var query = from c in Context.DETALLE_CREDITO.Include("PRODUCTO")
                            where c.PRODUCTO.Descripcion.ToUpper().Contains(descripcion.ToUpper())
                            && c.CreditoId.Equals(idCredito)
                            select c;

                return query.ToList();
            }
            else
            {
                var query = from c in Context.DETALLE_CREDITO.Include("PRODUCTO")
                            where c.CreditoId.Equals(idCredito)
                            orderby c.FechaDetalleCredito descending
                            select c;
                return query.ToList();
            }
        }

        public void RemoveDetalleCreditoByCreditoIdAndProductoId(int idCredito, int idProd)
        {
            var existe = Context.DETALLE_CREDITO.Where(c => c.CreditoId.Equals(idCredito) && c.PRODUCTO.Id.Equals(idProd)).SingleOrDefault();

            Context.DETALLE_CREDITO.Remove(existe);
            Context.SaveChanges();
        }


        public void UpdateDetalleCreditoByCreditoIdAndProductoId(int idCredito, int idProd)
        {
            var existe = Context.DETALLE_CREDITO.Where(c => c.CreditoId.Equals(idCredito) && c.PRODUCTO.Id.Equals(idProd)).SingleOrDefault();
            existe.Pagado = true;
            Context.Entry(existe).State = EntityState.Modified;
            Context.SaveChanges();
        }


        public bool GetAllDetallesCredByCreditoId(int idCredito)
        {
            var query = from c in Context.DETALLE_CREDITO.Include("CREDITO")
                        where c.CreditoId.Equals(idCredito)
                        select c;
            return query.Any();
        }
    }
}
